package TangramCore;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.geom.Rectangle2D;
import java.net.URL;

public class HladinaObrazek extends Hladina {
    Image img;
    boolean hidden;
    static int count = 0;
    int align;
    boolean maxSize;
    boolean cleared = true;
    Rectangle2D rect = new Rectangle2D.Double();
    
    public HladinaObrazek(/*String filename, Classres*/URL filename, MediaTracker mt, int a, boolean ms, Rectangle rp) {
        relpos = rp;
        align = a;
        maxSize = ms;
        img = Toolkit.getDefaultToolkit().getImage(filename);
        mt.addImage(img,count++);
        hidden = false;
    }
    
    @Override
    void clear(Graphics2D g) {
    }
    
    @Override    
    void draw(Graphics2D g) {
        if(hidden)
            return;
        int w = img.getWidth(null);
        int h = img.getHeight(null);
        if(maxSize){
            double kx = (double)pos.width/w, ky = (double)pos.height/h;
            if(kx < ky){
                w = pos.width;
                h = (int) (kx * h);
            } else{
                h = pos.height;
                w = (int) (ky * w);
            }
            h = pos.height;
        }
        int x = pos.x + (pos.width - w) / 2;
        int y = pos.y + (pos.height - h)/2;
        if( (align & TOP) != 0 )
            y = pos.y;
        else if( (align & BOTTOM) != 0)
            y = pos.y + pos.height - h;
        if( (align & LEFT) != 0 )
            x = pos.x;
        else if( (align & RIGHT) != 0)
            x = pos.x + pos.width - w;
        g.drawImage(img, x, y, w, h, null);
    }
    
    @Override    
    public void hide() {
        hidden = true;
        rect.setRect(pos);
    }
    
    @Override
    public void resize(Rectangle r) {
        pos = r;
        cleared = true;
    }
    
    @Override    
    public void show() {
        hidden = false;
        cleared = true;
    }
    
    @Override    
    void validate() {
        if(cleared)
            addRect2D(rect, pos);
        addRect2D(obr.rectUpdate, rect);
        rect.setRect(0,0,0,0);
        cleared = false;
    }
    
    public void toggleVisibility(){
        if(hidden)
            show();
        else
            hide();
    }

}
